package com.ht.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.ht.data.Result;
import com.ht.domin.bo.MembersBO;
import com.ht.domin.po.MembersOrder;
import com.ht.dto.MembersDTO;
import com.ht.dto.UserDTO;
import com.ht.em.ResultEnum;
import com.ht.service.MembersService;
import com.ht.util.JwtUtil;
import com.ht.utils.IdWorker;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * TODO 会员充值接口
 */
@RestController
@RequestMapping("members")
@Api("会员订单管理Api")
@RefreshScope //自动刷新配置文件
public class MembersController {

    @Autowired
    private MembersService membersService;

    /**
     * 提交订单
     */
    @PostMapping
    @ApiOperation(value = "增加订单")
    @ApiImplicitParam(name = "dto",value = "订单实体类",required = true,paramType = "body")
    public Result addMembers(@RequestBody MembersDTO dto,@RequestHeader("AuthToken")String token){
        //判断用户是否登录
        Claims claims = new JwtUtil().parseJwt(token);
        UserDTO userDTO = JSONUtil.toBean(claims.getSubject(), UserDTO.class);
        if (userDTO == null){
            return Result.response(ResultEnum.NO_LOGIN);
        }
        MembersBO bo = new MembersBO(dto);
        Result result = membersService.addMembersOrder(bo,userDTO);
        return result;
    }

    /**
     * 定时器查询会员到期时间
     */
    @Scheduled(cron = "0 0 */0 * * ?")
    public void findExpireTime(){
        //获取当前时间
        DateTime date = DateUtil.date();
        System.out.println("定时器执行" + date);
        List<MembersOrder> membersOrderList = membersService.findExpireTime();
        for (MembersOrder membersOrder : membersOrderList) {
            //判断当前会员状态是否为已过期
            if (!membersOrder.getStatus().equals("3")){
                //判断会员过期时间与当前时间
                if (membersOrder.getExpireTime().compareTo(date) < 0 || membersOrder.getExpireTime().compareTo(date) == 0){
                    membersService.updateStatus(membersOrder.getOrderNum());
                    System.out.println("会员状态修改成功");
                }
            }
        }
    }

}
